<template>
    <div>
        <!-- userWeekFormData -->
        <el-divider content-position="left">
            <el-text tag="b">学员周数据</el-text>
        </el-divider>
        <el-form inline>
            <!-- <el-form-item label="选择周次">
                <el-date-picker v-model="selectedDate" type="week" format="YYYY年 第ww周" value-format="YYYY-ww"
                    placeholder="选择周次" />
            </el-form-item> -->
            <el-form-item label="选择周次">
                <el-input v-model="weekFormat" type="week"> </el-input>
            </el-form-item>
            <el-form-item>
                <el-button-group>
                    <el-button type="primary" @click="handleSubmit">创建任务：学员周数据</el-button>
                </el-button-group>
            </el-form-item>
        </el-form>
    </div>
</template>

<script setup lang="ts">
import dayjs from 'dayjs';
import isoWeek from 'dayjs/plugin/isoWeek';
import weekOfYear from 'dayjs/plugin/weekOfYear';
import { ElMessage, ElMessageBox } from "element-plus";
import { computed, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useStore } from "vuex";
import { asyncAutoUserWeeklySummary } from '../../../api';
import { Storekey } from "../../../interface";
import Studycodemodel from "../../../mysql_interface/studycodemodel";
// 初始化dayjs插件
dayjs.extend(isoWeek)
dayjs.extend(weekOfYear);
// 设置周一为一周的第一天（1-6表示周一到周六，0是周日）
// dayjs.locale('zh-cn', { weekStart: 1 })

const router = useRouter()
const route = useRoute()
const store = useStore(Storekey)
const user = computed<Studycodemodel.Iuser>(() => {
    return store.getters.getuser;
});
const teamId = computed(() => {
    return user.value?.teamid
})

const weekSeparator = '-W'
const weekFormat = ref(getCurrentWeekFormat())
// 获取当前周的格式化字符串
function getCurrentWeekFormat() {
    return dayjs().format('YYYY-ww').replace('-', weekSeparator)
}

async function handleSubmit() {
    try {
        const [year, weekNumber] = weekFormat.value.split(weekSeparator).map(Number)
        console.log('选择的周:', weekFormat.value, '年份:', year, '周数:', weekNumber)
        // 添加确认弹窗
        await ElMessageBox.confirm(
            `确定要创建 ${year}年第${weekNumber}周 的学员周数据 统计任务吗？`,
            '确认操作',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        )
        await asyncAutoUserWeeklySummary({ year, week: weekNumber });
        ElMessage.success(`成功创建 ${year}年第${weekNumber}周 学员周数据总计任务`);
    } catch (error) {
        if (error instanceof Error) {
            ElMessage.error(error.message || '提交失败');
        }
    }
}
</script>

<style scoped>
.el-input {
    width: 200px;
}

.el-form-item {
    margin-right: 20px;
    margin-bottom: 0;
}

.el-button-group {
    margin-left: 10px;
}
</style>